
ALTER procedure sp_HopDong_CheckDaiLyTrung
@MaDaiLy varchar(4)
as
-- CHECK TRUNG MA DAI LY, TRA VE 1 NEU TRUNG, TRA VE 0 NEU KO TRUNG
	--IF EXISTS( SELECT * FROM(	
	--		SELECT B.MaDLMoi AS Ma_DaiLy
	--		, null as Ngay_ThanhLy
	--		,null as isTT
	--			FROM tblChuyenDL B
	--			WHERE Ngay = (SELECT MAX(NGAY) 
	--							FROM tblChuyenDL 
	--							WHERE HopDongID = B.HopDongID )
	--		UNION 
	--		SELECT A.Ma_DaiLy
	--		,A.Ngay_ThanhLy
	--		,A.isTT
	--		 FROM HOPDONG  A
	--		) DaiLy
	--		where Ma_DaiLy = @MaDaiLy and )
	--BEGIN	SELECT 1	END
	--ELSE	BEGIN	SELECT 0	END
	DECLARE @isValid INT = 0
	-- KIEM TRA CHO PHEP DAI LY DA THANH LY
	IF EXISTS (SELECT * FROM HOPDONG WHERE Ma_DaiLy = @MaDaiLy and isTT IS NULL 
	and Ngay_ThanhLy IS NOT NULL)
	BEGIN
		SET @isValid = 1
	END
	IF EXISTS  (SELECT * FROM tblChuyenDL B where MaDLMoi = @MaDaiLy )
	BEGIN
		SET @isValid = 1
	END
	SELECT @isValid
GO